package auth;

import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

import javax.enterprise.context.RequestScoped;
import javax.inject.Named;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;

import model.AccessType;
import model.PersistentEntity;
import model.User;

/**
 * 
 * @author Dennis Eicker
 * 
 */
@Named
@RequestScoped
public class SecurityManager {

	private User user;

	public SecurityManager() {
	}

	public SecurityManager(User user) {
		this();
		this.user = user;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public PersistentEntity checkPermission(PersistentEntity object) {
		if (object.getAccesstyp() == AccessType.PUBLIC) {
			return object;
		} else if (user != null && object.getAccessUsers().contains(user)) {
			return object;
		} else {
			throw new WebApplicationException(Response.Status.BAD_REQUEST);
		}
	}

	public Collection<PersistentEntity> checkPermission(List<PersistentEntity> list) {
		if (list == null || list.size()== 0) return new LinkedList<PersistentEntity>();
		if (list.get(0).getAccesstyp() == AccessType.PUBLIC) {
			return list;
		} else if (user != null && list.get(0).getAccessUsers().contains(user)) {
			return list;
		} else {
			throw new WebApplicationException(Response.Status.BAD_REQUEST);
		}
	}
}